package org.example.service.Impl;

import org.example.domain.Payload;
import org.example.domain.Permission;
import org.example.domain.UserDto;
import org.example.mapper.LoginMapper;
import org.example.service.LoginService;
import org.example.utils.JwtUtil;
import org.example.utils.Result;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

import static org.example.constant.Constants.*;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public Result login(String username, String password) {
        //拦截器已经判断该账号未登录过,所以要先登录

        //1.校验,账号,密码格式
        if (username == null || username.length() < 4 || username.length() > 20) return Result.error("用户名格式错误");
        if (password == null || password.length() < 4 || password.length() > 20)    return  Result.error("密码格式错误");
        // 2.查账号对应的用户信息
        UserDto  user =loginMapper.selectUserByName(username);
        // 3.判断加密后密码是否正确,用BCrypt做密码校验
        if(!BCrypt.checkpw(password,user.getPassword())){return Result.error("账号不正确或密码错误");}
        //4.正确就登录成功,生成access_token,和refresh_token,存储到redis中, at返回给客户端,
        //这里还要查用户的权限信息放到jwt里,存url字段
        List<Permission> permissions = loginMapper.selectPermissionsByUserId(user.getId());
        UserDto userDto = new UserDto(user.getId(), username, null);
        Payload payload = new Payload(userDto,permissions);
        String accessToken = JwtUtil.generateToken(payload);

        //将token存到redis中
        redisTemplate.opsForValue().set(String.format(REDIS_ACCESS_TOKEN,user.getId()),accessToken);
        return Result.success(accessToken);
    }
}
